// Copyright 2010 Jan Potoms. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


goog.require('extension.images.BrowserAction');
goog.require('extension.Settings');
goog.require('goog.net.ImageLoader');
goog.require('goog.events.EventType');


goog.provide('extension.BrowserAction');


goog.scope(function(){
  
  // import namespaces
  var ImageLoader = goog.net.ImageLoader;
  var Settings = extension.Settings;





  /** Provides functionality of the browser action
   * @constructor  
   */
  extension.BrowserAction = function() {
    
    this.context_ = document.createElement('canvas').getContext('2d');
    
    this.loadFrames_();
    
  };
  var BrowserAction = extension.BrowserAction;
  goog.addSingletonGetter(BrowserAction);
  



  
  /** The size of the icon.
  * @const 
  * @type {number}
  */
  BrowserAction.ICONSIZE = 19;
  
  /** Maximum value of the browseraction badge. (the badge can display up to 4 digits).
  * @const 
  * @type {number}
  */
  BrowserAction.BADGEMAXCOUNT = 9999;
  
  
  // fields
  BrowserAction.prototype.context_ = null; // for the drawing functions
  BrowserAction.prototype.frames_ = [];
  BrowserAction.prototype.animation_ = 0;
  BrowserAction.prototype.currFrame_ = 0;
  BrowserAction.prototype.stopAnimation_ = false;
  
  
  
  
  
  
  /** Sets the color of the icon.
   * 
   * @param {string} color The desired color in CSS format. Only '#FFFFFF' style is supported.
   */
  BrowserAction.prototype.setColor = function (color) {
    for(var i = 0; i < this.frames_.length; i++) {
      this.context_.clearRect(0, 0, BrowserAction.ICONSIZE , BrowserAction.ICONSIZE);
      
      this.context_.putImageData(this.frames_[i], 0, 0);
      
      this.context_.globalCompositeOperation = 'source-in';
      this.context_.fillStyle = color;
      this.context_.fillRect(0, 0, BrowserAction.ICONSIZE, BrowserAction.ICONSIZE );
      
      this.frames_[i] = this.context_.getImageData(0, 0, BrowserAction.ICONSIZE, BrowserAction.ICONSIZE);
    }
    
    // set badge color.    
    var rgb = color.match(/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/);    
    chrome.browserAction.setBadgeBackgroundColor({
      color: [
        parseInt(rgb[1], 16),
        parseInt(rgb[2], 16),
        parseInt(rgb[3], 16),
        255
      ]
    });
  };
  
  /** Sets the unread count in the badge.
   * 
   * @param {number} count The number to be displayed in the badge.
   */
  BrowserAction.prototype.setCount = function (count) {
    
    var badgeText = '';    
    if(count > 0) {
      // clamp the badge text to its maximum.
      badgeText = Math.min(count, BrowserAction.BADGEMAXCOUNT) + '';
    }
     
    chrome.browserAction.setBadgeText({
      text: badgeText
    });
    
  };
  
  
  /** Loads the frames for the browseraction animation.
   * @private
   * 
   * @return undefined
   */
  BrowserAction.prototype.loadFrames_ = function () {
    var frameUrls = extension.images.BrowserAction.getFrames();
    var loader = new ImageLoader();
    
    var loaded = 0;
    
    // add the image to the frames collection after loading.
    loader.addEventListener(goog.events.EventType.LOAD, function (e) {
      
      this.context_.clearRect(0, 0, BrowserAction.ICONSIZE, BrowserAction.ICONSIZE);
      this.context_.drawImage(e.target, 0, 0, BrowserAction.ICONSIZE, BrowserAction.ICONSIZE);
      
      this.frames_[e.target.id] = this.context_.getImageData(0, 0, BrowserAction.ICONSIZE, BrowserAction.ICONSIZE);
      loaded += 1;
      
      if(loaded === frameUrls.length) {
        // All images are loaded.
      }
    }, true, this);
    
    for(var i = 0; i < frameUrls.length; i++) {
      loader.addImage(i + '', frameUrls[i]);
    }
    
    loader.start();
  };
  
  
  
  /** Starts the loading animation.
   * 
   * @return undefined
   */
  BrowserAction.prototype.startLoadingAnimation = function () {
    
    this.stopAnimation_ = false;
      
    if(!this.animation_) {
      // Only start animation when no animation is busy.
      
      this.animation_ = setInterval(goog.bind(function () {
        
        // Advance the current frame and draw the icon. 
        this.currFrame_ += 1;
        if(this.currFrame_ >= this.frames_.length) {
          this.currFrame_ = 0;
          
          // Stop the animation if requested.
          if(this.stopAnimation_) {
            clearInterval(this.animation_);
            this.animation_ = undefined
          }
        }
        
        chrome.browserAction.setIcon({imageData: this.frames_[this.currFrame_]});
        
      }, this), Settings.getBrowserActionAnimationInterval());
    }
    
  };
  
  
  /** Stops the loading animation.
   * 
   * @return undefined
   */
  BrowserAction.prototype.stopLoadingAnimation = function () {
    this.stopAnimation_ = true;
  };  
  

});